package vc.learn.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.*;
import org.springframework.cloud.client.loadbalancer.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.*;
import vc.learn.springcloud.dto.User;

/**
 * Created on 2018-06-30 下午9:07.
 *
 * @author <a href="mailto:vague.fu@outlook.com">vague.fu</a>
 * @version 0.0.1
 * @since 0.0.1
 */
@Slf4j
@RestController
public class MovieController {

    private RestTemplate restTemplate;
    private LoadBalancerClient loadBalancerClient;

    public MovieController(RestTemplate restTemplate, LoadBalancerClient loadBalancerClient) {
        this.restTemplate = restTemplate;
        this.loadBalancerClient = loadBalancerClient;
    }

    @GetMapping("/user/{id}")
    @HystrixCommand(fallbackMethod = "findByIdFallBack",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000"),
            @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "10000")
    },threadPoolProperties = {
            @HystrixProperty(name = "coreSize",value = "1"),
            @HystrixProperty(name = "maxQueueSize",value = "10")
    })
    public User findById(@PathVariable Long id) {
        return this.restTemplate.getForObject("http://microservice-provider-user/" + id, User.class);
    }

    public User findByIdFallBack(Long id){
        User user = new User();
        user.setId(-1L);
        user.setName("默认用户");
        return user;
    }

    @GetMapping("/log-user-instance")
    public void logUserInstance() {
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user");

        log.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort());
    }
}
